package com.forum.servlet;

import com.forum.bean.Comment;
import com.forum.dao.CommentDao;
import com.forum.util.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by young on 2017/5/29.
 *
 * @version 1.0
 */
@WebServlet(name = "CommentServlet", urlPatterns = "/addComment")
public class CommentServlet extends HttpServlet {
    /**
     * 获取评论获得参数，传参数给CommentDao()
     *
     * @param request  接受前端的参数
     * @param response 返回参数
     * @throws ServletException 异常
     * @throws IOException      异常
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("content-type", "text/html;charset=UTF-8");
        Comment comment = new Comment();
        comment.setComment(request.getParameter("comment"));
        String topicId = request.getParameter("topic_id");
        String userId = request.getParameter("user_id");
        String date = DateUtil.getDate();
        comment.setDate(date);
        CommentDao commentDao = new CommentDao();
        int row = commentDao.addComment(Integer.parseInt(topicId), Integer.parseInt(userId), comment);
        if (row == 1) {
            response.sendRedirect("/article.jsp?topic_id=" + topicId);
        } else {
            PrintWriter out = response.getWriter();
            out.println("评论失败！");

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}
